#! /bin/bash
set -x
set -e
set -u

# Figure out if we have wget or curl
if which wget >/dev/null; then
  http_get="wget --output-document=- --quiet"
elif which curl >/dev/null; then
  http_get="curl -o -"
else
  echo "Error: could not find wget or curl on the remote system."
  echo "To install Puppet Enterprise using HTTP, wget or curl are required"
  exit 1
fi

# The installer action determines a temporary directory internally
# This is not a user defined option.  You may assume this will be
# a unique string of characters.
tmpdir='<%= options[:tmp_dir] %>'
cd "${tmpdir}"

<% if not options[:autogenerated_certname] %>
# If the puppet agent certname has been given on the command line using
# --puppetagent-certname=foobar then we should replace it in the answers file.
# (Note, the answers file has been uploaded by the face action)
# Finally, actually install Puppet Enterprise
# Let's play shuffle the files.
mv puppet.answers puppet.answers.orig
# Give me everything _except_ any agent certname specified in the answers file
grep -v '^q_puppetagent_certname' puppet.answers.orig > puppet.answers
# Append the user specified option from the command line arguments.
echo 'q_puppetagent_certname=<%= options[:puppetagent_certname] %>' >> puppet.answers
<% else %>
#If we have a certname specified in the answers file, use it
if ! grep '^q_puppetagent_certname' puppet.answers; then
  echo 'q_puppetagent_certname=<%= options[:puppetagent_certname] %>' >> puppet.answers
fi
<% end %>

echo "Installation script has started..."
echo "Downloading from: <%= options[:installer_payload] %>"

# Create a new directory to decompress the Puppet Enterprise installer
# into.  This provides us with consistent pathing regardless of the PE
# version.
install_dir="puppet-enterprise"
if [[ ! -e "${install_dir}" ]]; then
  mkdir "${install_dir}"
fi

# We assume the payload is a tar.gz file because the option handler
# enforces this.
# To save disk space (I'm concerned about /tmp filling) decompress on the fly.
echo "Uncompressing the payload ..."
$http_get '<%= options[:installer_payload] %>' | \
  tar -xvzf - --strip-components 1 -C "${install_dir}"
# REVISIT (This assumes GNU tar with the --strip-components option)
echo "Uncompressing the payload ... Done."

# Install Puppet Enterprise
"${install_dir}"/puppet-enterprise-installer -a puppet.answers 2>&1 | tee install.log

# Finally, set up any custom facts if necessary
mkdir -p /etc/puppetlabs/facter/facts.d
<% if options[:facts] %>
echo "Installing custom facts"
<% options[:facts].each do |fact,value| %>
echo <%= fact %>=<%= value %> > /etc/puppetlabs/facter/facts.d/<%= fact %>.txt
<% end %>
<% end %>

# And then kick off a puppet agent run
/opt/puppet/bin/puppet agent --daemonize \
  --onetime \
  --ignorecache \
  --no-usecacheonfailure \
  --detailed-exitcodes \
  --no-splay

# vim:ft=sh
